package com.winning.devops.batch.processor.ch01.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.devops.batch.processor.ch01.domain.Customer;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStreamWriter;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 多文件输出相关配置
 * <p>
 * reader writer
 *
 * @author chensj
 * @date 2020-03-07 18:30
 */
@Configuration
public class ProcessorItemConfig {

    @Autowired
    private DataSource dataSource;

    /**
     * Jdbc分页读取
     *
     * @return ItemReader
     */
    @Bean
    public ItemReader<? extends Customer> processorFileItemDemoReader() {
        JdbcPagingItemReader<Customer> reader = new JdbcPagingItemReader<>();
        reader.setDataSource(dataSource);
        reader.setPageSize(10);
        // 数据库记录转换实体类
        reader.setRowMapper(new RowMapper<Customer>() {
            @Override
            public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {

                Customer user = new Customer();
                user.setId(rs.getInt(1));
                user.setFirstName(rs.getString(2));
                user.setLastName(rs.getString(3));
                user.setBirthday(rs.getString(4));
                return user;
            }
        });
        // 指定查询语句 SQL
        MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider();
        // 指定查询那些字段
        provider.setSelectClause("id,firstName,lastName,birthday");
        // 指定查询那张表
        provider.setFromClause("FROM customer");
        // 指定根据那个字段进行排序
        Map<String, Order> sortKeys = new HashMap<>(1);
        // 设置ID排序
        sortKeys.put("ID", Order.ASCENDING);
        provider.setSortKeys(sortKeys);
        // 指定数据库查询信息
        reader.setQueryProvider(provider);
        return reader;
    }

    /**
     * 输出信息到 普通文件
     *
     * @return ItemWriter
     * @throws Exception
     */
    @Bean
    public ItemStreamWriter<? super Customer> processorFlatFileDemoWriter() throws Exception {
        FlatFileItemWriter<Customer> writer = new FlatFileItemWriter<>();
        // 指定编码
        writer.setEncoding(Charset.forName("UTF-8").name());
        // 指定输出文件
        writer.setResource(new FileSystemResource("g:\\processor-test.txt"));
        // 指定转换
        writer.setLineAggregator(new LineAggregator<Customer>() {
            ObjectMapper mapper = new ObjectMapper();

            @Override
            public String aggregate(Customer item) {
                String str = null;
                try {
                    str = mapper.writeValueAsString(item);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return str;
            }
        });
        writer.afterPropertiesSet();
        return writer;
    }
}
